package com.itheima.health.service.impl;

import com.itheima.health.dao.UserDao;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    /**
     * 用户注册
     * @param registerUser
     * @return
     */
    @Override
    public Result register(User registerUser) {
        // 调用查询方法，查询用户是否存在
        User queryUser = userDao.findByUsername(registerUser.getUsername());
        if (queryUser != null) {
            return new Result(false, "注册失败, 用户名已存在");
        }

        // 调用方法查看手机号是否已经存在
        queryUser = userDao.findByTelephone(registerUser.getTelephone());
        if (queryUser != null) {
            return new Result(false, "注册失败, 该手机号已被注册!");
        }

        // 给密码加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String bcryptPassword = encoder.encode(registerUser.getPassword());
        registerUser.setPassword(bcryptPassword);
        // 把用户数据添加到数据库
        userDao.insert(registerUser);

        return new Result(true, "注册成功");
    }

    /**
     * 用户登录
     * @param loginUser
     * @return
     */
    @Override
    public Result login(User loginUser, HttpSession session) {
        User user = userDao.findByUsername(loginUser.getUsername());
        if (user == null) {
            return new Result(false, "登录失败, 用户名不存在!");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean flag = encoder.matches(loginUser.getPassword(), user.getPassword());
        System.out.println("flag = " + flag);
        if (flag) {
            session.setAttribute("loginUser",user);
            return new Result(true, "登录成功");
        } else {
            return new Result(false, "登录失败, 密码错误!");
        }
    }

    @Override
    public User findByTelephone(String telephone) {
        User user = userDao.findByTelephone(telephone);
        // 返回查询到的用户
        return user;
    }
}